package znet

import (
	"fmt"
	"net"
	"zinx/utils"
	"zinx/ziface"
)

type Server struct {
	Name      string
	IPVersion string
	IP        string
	Port      int
	Router    ziface.IRouter
}

//func CallBackToClient(conn *net.TCPConn,data []byte,cnt int) error {
//	fmt.Printf("[Conn Handle] CallBackToClient...\n")
//	if _,err := conn.Write(data[:cnt]);err != nil {
//		return errors.New("CallBackToClient error")
//	}
//	return nil
//}

func (s *Server) Start() {
	fmt.Printf("[zinx] server [globalobj:%+v]  is starting... \n",utils.GlobalObject)
	go func() {
		addr, err := net.ResolveTCPAddr(s.IPVersion, fmt.Sprintf("%s:%d", s.IP, s.Port))
		if err != nil {
			fmt.Printf("get tcp addr err \n")
			return
		}

		lisenner, err := net.ListenTCP(s.IPVersion, addr)
		if err != nil {
			fmt.Printf("get tcp lisenner err \n")
			return
		}

		fmt.Printf("[zinx] start zinx server[%s]success,now listenning...\n", s.Name)
		var cid uint32

		for {
			conn, err := lisenner.AcceptTCP()
			if err != nil {
				fmt.Printf("accept err\n")
				continue
			}
			//go func () {
			//	for {
			//		buf := make([]byte,512)
			//		cnt,err :=conn.Read(buf)
			//
			//		fmt.Printf("server recv:%s,cnt=%d \n",buf,cnt)
			//		if err != nil {
			//			fmt.Printf("recv buf err",err)
			//			continue
			//		}
			//		if _,err = conn.Write(buf[:cnt]);err!= nil {
			//			fmt.Printf("write back buf err\n")
			//			continue
			//		}
			//	}
			//}()
			dealConn := NewConnection(conn, cid, s.Router)
			cid++
			go dealConn.Start()
		}
	}()
}

func (s *Server) Stop() {

}

func (s *Server) Serve() {
	s.Start()
	select {}
}

func (s *Server) AddRouter(router ziface.IRouter) {
	s.Router = router
}

func NewServer(name string) ziface.IServer {
	s := &Server{
		Name:      utils.GlobalObject.Name,
		IPVersion: "tcp4",
		IP:        utils.GlobalObject.Host,
		Port:      utils.GlobalObject.TcpPort,
		Router:    nil,
	}
	return s
}
